package com.schuxl.htmlobserver.observer;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import com.schuxl.htmlobserver.dataobject.Autoscout24Ad;
import com.schuxl.htmlobserver.dataobject.schemaTypen.sites.Sites.Site;

public class Autoscout24HtmlObserver extends HtmlObserver<Autoscout24Ad> {


	private static final String START = "cars=new Array();";
	private static final String END = "//]]";
	
	
	public Autoscout24HtmlObserver(Site site) {
		super(site);
	}

	
	
	
	
	@Override
	protected List<Autoscout24Ad> getCurrentList(Document document) {
		List<Autoscout24Ad> currentList = new ArrayList<Autoscout24Ad>();
		Autoscout24Ad autoscout24Ad = null;

		Elements elements = document.select("script");
		Element element = null;
		for(Element e : elements) {
 			if(e!=null && e.childNodes().size()>0 && e.childNode(0).toString().contains("var cars=new Array()")) { //Das <script> Tag mit dem Seitencontent herausfinden
 				element = e;
 				break;
 			}
		}
		String script = element.childNode(0).toString();
		String content = script.substring(script.indexOf(START)+START.length());	//prefix entfernen
		content = content.substring(0, content.indexOf(END));	//suffix entfernen

		String[] items = content.split("cars\\["); //items enthaelt alle Fahrzeuge
		for(int i=0; i<items.length; i++) { 
			String item = items[i]; //item enthaelt genau EIN Fahrzeug
			String[] attributes = item.split("'"); //attributes enthaelt alle Attribute eines Fahrzeuges
			if(attributes.length<2)
				continue;
			
			autoscout24Ad = new Autoscout24Ad();
			autoscout24Ad.setTitle(attributes[21]);
			autoscout24Ad.setLink(attributes[5]);
			autoscout24Ad.setImageLink((attributes[1].contains(".gif"))?null:attributes[1]);
			autoscout24Ad.setYear(attributes[15].contains("-/-")?2013:Integer.parseInt(attributes[15].substring(attributes[15].length()-4)));
			autoscout24Ad.setKilometers(attributes[13].replaceAll("\\D+",""));
			autoscout24Ad.setPrice(Integer.parseInt(attributes[7].replaceAll("\\D+","")));
			autoscout24Ad.setLocation(attributes[27]+" "+attributes[29] );
			currentList.add(autoscout24Ad);

		}
				
		return currentList;
	}
			
				
	

	
	
	
}
